<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="课程编号" prop="courseCode">
        <el-input
            v-model="queryParams.courseCode"
            placeholder="请输入课程编号"
            style="width: 200px;"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
            v-model="queryParams.courseName"
            placeholder="请输入课程名称"
            style="width: 200px;"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程英文名称" prop="courseNameEn">
        <el-input
            v-model="queryParams.courseNameEn"
            style="width: 200px;"
            placeholder="请输入课程英文名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开课学院" prop="collegeId">
        <el-select
            v-model="queryParams.collegeId"
            placeholder="请选择开课学院"
            filterable
            style="width: 200px;"
            clearable
        >
          <el-option v-for="item in collegeList"
                     :key="item.collegeId"
                     :label="item.collegeName"
                     :value="item.collegeCode">  <!-- 注意：这里用 collegeCode 作为 value -->
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开课学期" prop="semester">
        <el-select v-model="queryParams.semester" placeholder="请选择开课学期" clearable style="width: 200px;">
          <el-option
              v-for="dict in semester"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程性质" prop="courseNature">
        <el-select v-model="queryParams.courseNature" placeholder="请选择课程性质" clearable style="width: 200px;">
          <el-option
              v-for="dict in characteristics_of_the_course"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程类型" prop="courseType">
        <el-select v-model="queryParams.courseType" placeholder="请选择课程类型" clearable style="width: 200px;">
          <el-option
              v-for="dict in type_of_course"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开课状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择开课状态" clearable style="width: 200px;">
          <el-option
              v-for="dict in course_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleView"
        >查看详情</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['course:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['course:course:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="课程编号" align="center" prop="courseCode" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="课程英文名称" align="center" prop="courseNameEn" />
      <el-table-column label="开课学院" align="center">
        <template #default="scope">
          {{ collegeList.find(item => item.collegeCode === scope.row.collegeId)?.collegeName || '无' }}
        </template>
      </el-table-column>

      <el-table-column label="课程学分" align="center" prop="credits" />
      <el-table-column label="总学时" align="center" prop="totalHours" />
      <el-table-column label="开课学期" align="center" prop="semester">
        <template #default="scope">
          <dict-tag :options="semester" :value="scope.row.semester"/>
        </template>
      </el-table-column>
      <el-table-column label="课程性质" align="center" prop="courseNature">
        <template #default="scope">
          <dict-tag :options="characteristics_of_the_course" :value="scope.row.courseNature"/>
        </template>
      </el-table-column>
      <el-table-column label="课程类型" align="center" prop="courseType">
        <template #default="scope">
          <dict-tag :options="type_of_course" :value="scope.row.courseType"/>
        </template>
      </el-table-column>
      <el-table-column label="开课状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="course_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['course:course:view']">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['course:course:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['course:course:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 导入对话框 -->
    <el-dialog :title="upload.titleImport" v-model="upload.openImport" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          drag
          @change="handleFileChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center">
          <div>
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="handleCancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listCourse, getCourse, delCourse, addCourse, updateCourse,importCourseData,viewCourse  } from "@/api/course/course";
import { listCollege } from "@/api/college/college";
import { ref, reactive, toRefs } from "vue";
import { loadAllParams } from "@/api/page";
import { listMajor, getMajorByCollegeId } from "@/api/major/major";
import { getCurrentInstance } from 'vue';
import { getToken } from "@/utils/auth";
import {useRouter} from 'vue-router';

const router = useRouter();
const { proxy } = getCurrentInstance();
const { characteristics_of_the_course, type_of_course, semester, audit_status, course_status, grade_type, examination_method, teaching_language } = proxy.useDict('characteristics_of_the_course', 'type_of_course', 'semester', 'audit_status', 'course_status','grade_type','examination_method','teaching_language');

const courseList = ref([]);
const open = ref(false);
const loading = ref(true);

const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const importFile = ref(null);

// 学院和专业列表
const collegeList = ref([]);
const zyZlist = ref([]); // 所有专业列表，用于显示名称
const majorList = ref([]);

// 导入相关配置
const upload = ref({
  titleImport: "",
  openImport: false,
  isUploading: false,
  updateSupport: false,
  headers: {
    Authorization: "Bearer " + getToken()
  },
  url: "/course/course/importData",
});

const uploadRef = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseCode: null,
    courseName: null,
    courseNameEn: null,
    collegeId: null,//开课学院
    applicableDepartments:null,//适用学院
    applicableMajors: null, // 确保添加了 applicableMajors适用专业
    credits: null,
    totalHours: null,
    semester: null,
    courseNature: null,
    examinationMethod: null,
    gradeType: null,
    courseType: null,
    teachingMethod: null,
    prerequisiteCourses: null,
    courseIntroduction: null,
    teachingLanguage: null,
    referenceBooks: null,
    status: null
  },
  rules: {
    courseCode: [
      { required: true, message: "课程编号不能为空", trigger: "blur" }
    ],
    courseName: [
      { required: true, message: "课程名称不能为空", trigger: "blur" }
    ],
    courseNameEn: [
      { required: true, message: "课程英文名称不能为空", trigger: "blur" }
    ],
    collegeId: [
      { required: true, message: "开课院校不能为空", trigger: "blur" }
    ],
    credits: [
      { required: true, message: "课程学分，支持小数，如 3.5 学分不能为空", trigger: "blur" }
    ],
    totalHours: [
      { required: true, message: "总学时不能为空", trigger: "blur" }
    ],
    semester: [
      { required: true, message: "开课学期不能为空", trigger: "change" }
    ],
    courseNature: [
      { required: true, message: "课程性质不能为空", trigger: "change" }
    ],
    courseType: [
      { required: true, message: "课程类型不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "开课状态不能为空", trigger: "change" }
    ],
    examinationMethod: [
      { required: true, message: "考核方式不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询课程信息列表 */
function getList() {
  loading.value = true;
  listCourse(queryParams.value).then(response => {
    courseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    courseCode: null,
    courseName: null,
    courseNameEn: null,
    collegeId: null,
    applicableDepartments: null,
    // applicableMajors: null,
    credits: null,
    totalHours: null,
    semester: null,
    courseNature: null,
    examinationMethod: null,
    gradeType: null,
    teachingMethod: null,
    courseType: null,
    prerequisiteCourses: null,
    courseIntroduction: null,
    teachingLanguage: null,
    referenceBooks: null,
    // applicableMajors: null,
    status: null
  };
  proxy.resetForm("courseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  // 重置时清空专业列表和专业选择
  majorList.value = [];
  queryParams.value.applicableMajors = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增课程
const handleAdd = () => {
  router.push({
    path: '/course/detail',
    query: {
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize
    }
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const id = row?.id || ids.value[0]
  router.push({
    path: `/course/detail/${id}`,
    query: {
      mode: 'edit',
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      courseCode: queryParams.value.courseCode,
      courseName: queryParams.value.courseName,
      courseNameEn: queryParams.value.courseNameEn,
      collegeId: queryParams.value.collegeId,
      applicableDepartments: queryParams.value.applicableDepartments,
      // applicableMajors: queryParams.value.applicableMajors, // 添加 majorId
      credits: queryParams.value.credits,
      totalHours: queryParams.value.totalHours,
      semester: queryParams.value.semester,
      courseNature: queryParams.value.courseNature,
      examinationMethod: queryParams.value.examinationMethod,
      gradeType: queryParams.value.gradeType,
      courseType: queryParams.value.courseType,
      teachingMethod: queryParams.value.teachingMethod,
      prerequisiteCourses: queryParams.value.prerequisiteCourses,
      courseIntroduction: queryParams.value.courseIntroduction,
      teachingLanguage: queryParams.value.teachingLanguage,
      referenceBooks: queryParams.value.referenceBooks,
      // applicableMajors: queryParams.value.applicableMajors,
      status: queryParams.value.status
    }
  });
}

/** 查看详情按钮操作 */
const handleView = (row) => {
  const id = row?.id || ids.value[0]
  router.push({
    path: `/course/detail/${id}`,
    query: {
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["courseRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除课程库中信息编号为"' + _ids + '"的数据项？').then(function() {
    return delCourse(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('course/course/export', {
    ...queryParams.value
  }, `course_${new Date().getTime()}.xlsx`)
}

/** 学院变化处理函数 - 修复版本 */
function handleApplicableCollegeChange(collegeCode) {  // 参数名改为 collegeCode，因为传入的是 collegeCode
  console.log('选中的院校代码:', collegeCode);

  if (!collegeCode) {
    majorList.value = [];
    queryParams.value.applicableMajors = null;
    return;
  }

  // 调用API查询该院系下的专业 - 注意传入的是 collegeCode
  getMajorByCollegeId(collegeCode).then(response => {
    majorList.value = response.rows;
    console.log('获取到的专业列表:', majorList.value);
    // 清空之前的专业选择
    queryParams.value.applicableMajors = null;
    if (form.value) {
      form.value.applicableMajors = null;
    }
  }).catch(error => {
    console.error('获取专业列表失败:', error);
    majorList.value = [];
  });
}
/** 获取学院列表信息 */
function getCollegeList() {
  loading.value = true;
  listCollege(loadAllParams).then(response => {
    collegeList.value = response.rows;
    console.log('学院列表:', collegeList.value);
    total.value = response.total;
    loading.value = false;
  });
}

  // 获取所有专业列表，用于显示名称
function getlistMajor() {
  loading.value = true;
  listMajor(loadAllParams).then(response => {
    zyZlist.value = response.rows;
    console.log('所有专业列表:', zyZlist.value);
    total.value = response.total;
    loading.value = false;
  });
}
/** 通过学院id获取学院名称 */
const getCollegeName = (collegeId) => {
  if (collegeId) {
    const college = collegeList.value.find(item => item.collegeId === collegeId);
    return college ? college.collegeName : '无';
  }
  return '无';
};

/** 通过专业id获取专业名称 */
const getMajorName = (applicableMajors) => {
  if (applicableMajors) {
    const major = zyZlist.value.find(item => item.applicableMajors === applicableMajors);
    return major ? major.majorName : '无';
  }
  return '无';
};

/** 导入相关方法 */
function handleImport() {
  console.log('准备打开导入对话框');
  upload.value.isUploading = false;
  upload.value.updateSupport = false;

  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }

  upload.value.titleImport = "导入课程信息表";
  upload.value.openImport = true;
  console.log('导入对话框状态:', upload.value.openImport);
}

function handleCancelImport() {
  console.log('关闭导入对话框');
  upload.value.openImport = false;
  upload.value.isUploading = false;
  importFile.value = null;

  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
      import.meta.env.VUE_APP_BASE_API + '/course/course/exportTemplate',
      {
        ...queryParams.value
      },
      `课程信息模板${new Date().getTime()}.xlsx`
  );
}

/** 文件上传中处理 */
function handleFileUploadProgress(event, file, fileList) {
  console.log('===== 上传进度 =====');
  console.log('进度百分比:', Math.round(event.percent) + '%');
  console.log('当前文件:', file.name);
  upload.value.isUploading = true;
}

/** 文件上传成功处理 */
function handleFileSuccess(response, file, fileList) {
  console.log('===== 上传成功 =====');
  console.log('后端响应内容:', response);
  console.log('上传成功的文件:', file.name);
  upload.value.openImport = false;
  upload.value.isUploading = false;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  proxy.$alert(response.msg, "导入结果", {
    dangerouslyUseHTMLString: true
  });
  getList();
}

/** 提交上传文件 */
function submitFileForm() {
  if (!importFile.value) {
    proxy.$message.warning('请选择要上传的文件');
    return;
  }

  console.log('使用保存的文件:', importFile.value.name);
  console.log('updateSupport参数:', upload.value.updateSupport);

  upload.value.isUploading = true;
  importCourseData(importFile.value, upload.value.updateSupport)
      .then(response => {
        upload.value.isUploading = false;
        upload.value.openImport = false;
        importFile.value = null;
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }
        proxy.$message.success(response.msg || '导入成功');
        getList();
      })
      .catch(error => {
        upload.value.isUploading = false;
        console.error('上传失败:', error);
        proxy.$message.error('上传失败: ' + (error.message || '未知错误'));
      });
}

/** 文件上传错误处理 */
function handleFileError(err, file, fileList) {
  console.error('===== 上传错误详情 =====');
  console.error('错误对象:', err);
  console.error('请求URL:', upload.value.url + '?updateSupport=' + upload.value.updateSupport);
  console.error('响应状态码:', err.response?.status);
  console.error('响应内容:', err.response?.data);
  console.error('错误消息:', err.message);
  upload.value.isUploading = false;
  proxy.$message.error('上传失败: ' + (err.message || '未知错误'));
}

/** 文件列表改变时触发 */
function handleFileChange(file, fileList) {
  console.log('选择的文件:', file);
  console.log('文件列表:', fileList);
  importFile.value = file.raw || file;
}

// 初始化
getCollegeList();
getList();
</script>